Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

Note: if you are using the Udacity workspace, you DO NOT need to re-download these - they can be found in the /data folder as noted in the cell below.

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dog_images.

  • Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [1]:
import numpy as np 
from glob import glob

# load files from human and dogs 
human_files = np.array(glob('/data/lfw/*/*'))
dog_files = np.array(glob('/data/dog_images/*/*/*'))

#print number of images in each dataset

print('There are {} total human images.'.format(len(human_files)))
print('There are {} total dog images.'.format(len(dog_files)))
There are 13233 total human images.
There are 8351 total dog images.
In [2]:
# import liberaries
import torch 
import torchvision.models as models
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

from torchvision import datasets
from PIL import ImageFile
from PIL import Image
import PIL

ImageFile.LOAD_TRUNCATED_IMAGES = True

use_cuda = torch.cuda.is_available()

if use_cuda:
    print('cuda is avaliable ... ' )
    
print('PyToch Version : ',torch.__version__)
cuda is avaliable ... 
PyToch Version :  0.4.0

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

The following code example will use pretrained Haar cascade models to detect faces in an image. First, a CascadeClassifier is created and the necessary XML file is loaded using the CascadeClassifier::load method. Afterwards, the detection is done using the CascadeClassifier,detectMultiScale method, which returns boundary rectangles for the detected faces.

In [85]:
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline

# 1. extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
                         
# 2. load image (rgb)
img_rgb = cv2.imread(human_files[125])
                                     
#3. convert image to grayscale
img_gray =  cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
                                     
#4. find faces in image
faces = face_cascade.detectMultiScale(img_gray)
                                     
#5. print num of faces detected  in image
print('Numbrer of faces detected = {}'.format(len(faces)))
                                     
#6. get bounding box for each detected face
for x, y, w, h in faces:
    # add bounded box to the colored image
    # cv2.rectangle(image, start_point, end_point, color, thickness)
    cv2.rectangle(img_rgb, (x, y), (x+w, y+h), (255,0,0) , 2)
    
#7. Convert RGB image to RGB image for plotting
face_rgb = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2RGB)
#8. display the image, along with bounding box
plt.imshow(face_rgb)
plt.show()
Numbrer of faces detected = 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [70]:
# returns "True" if face is detected in image stored at img_path
#from mtcnn import MTCNN

def face_detector(img_path):
    
    img_rgb = cv2.imread(img_path)
    img_gray= cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
    faces = face_cascade.detectMultiScale(img_gray)
    
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: The face detector isn't perfect as it detect face in 16% of dog images. and it fails to detect 4% of human images.

In [5]:
from tqdm import tqdm_notebook as tqdm

def face_detector_performance(files_short , file_name):
    counter = []
    incorrect_imgs = []
    
    [(incorrect_imgs.append(file)) if ((face_detector(file))^bool(file_name =='human')) else (counter.append(1))for file in tqdm(files_short) ]

    return sum(counter), incorrect_imgs   
In [6]:
total = 100
human_files_short = human_files[:total]
dog_files_short = dog_files[:total]

n_faces_in_human_files, error_list_human_files  = face_detector_performance(human_files_short, 'human')
n_faces_in_dog_files  , error_list_dog_files    = face_detector_performance(dog_files_short, 'dog')


In [8]:
print('Number of faces detected in human files short is {}/{} \t\t cost = {}%'.format(n_faces_in_human_files, total,
                                                                                           100-n_faces_in_human_files))
print('Number of faces detected in dog files short is {}/{}   \t\t cost = {}%'.format(100-n_faces_in_dog_files, total,
                                                                                         100-n_faces_in_dog_files))
Number of faces detected in human files short is 96/100 		 cost = 4%
Number of faces detected in dog files short is 16/100   		 cost = 16%
In [8]:
error_list_human_files
#error_list_dog_files 
Out[8]:
['/data/lfw/Rafael_Vinoly/Rafael_Vinoly_0001.jpg',
 '/data/lfw/Julianne_Moore/Julianne_Moore_0002.jpg',
 '/data/lfw/Nick_Price/Nick_Price_0001.jpg',
 '/data/lfw/Clive_Lloyd/Clive_Lloyd_0001.jpg']
In [22]:
# Display images
def show_erroneous (my_list, row, col, size):
    plt.figure(figsize=(20,20))   

    for i, img in enumerate(my_list):
              
        image = PIL.Image.open(img)
        plt.subplot(row,col,i+1)
        plt.title(img.split('/')[-1].split('.')[0] , size = size)
        plt.axis('off')
        plt.imshow(image);
        print
In [12]:
# print detector errors form human files 
show_erroneous(error_list_human_files, 2,2,20)
In [13]:
# print detector errors form dog files 
show_erroneous(error_list_dog_files, 4,4,15)

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

Face Detector using MTCNN

doesn't work

In [ ]:
!pip install mtcnn
In [15]:
import mtcnn
# print version
print(mtcnn.__version__)
Using TensorFlow backend.
/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:458: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:459: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:460: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:461: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:462: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:465: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-15-ce93d908b53d> in <module>()
----> 1 import mtcnn
      2 # print version
      3 print(mtcnn.__version__)

/opt/conda/lib/python3.6/site-packages/mtcnn/__init__.py in <module>()
     24 # SOFTWARE.
     25 
---> 26 from mtcnn.mtcnn import MTCNN
     27 
     28 

/opt/conda/lib/python3.6/site-packages/mtcnn/mtcnn.py in <module>()
     35 
     36 from mtcnn.exceptions.invalid_image import InvalidImage
---> 37 from mtcnn.network.factory import NetworkFactory
     38 
     39 

/opt/conda/lib/python3.6/site-packages/mtcnn/network/factory.py in <module>()
     24 # SOFTWARE.
     25 
---> 26 from keras.layers import Input, Dense, Conv2D, MaxPooling2D, PReLU, Flatten, Softmax
     27 from keras.models import Model
     28 

ImportError: cannot import name 'Softmax'
In [ ]:
from mtcnn import MTCNN
from matplotlib.patches import Rectangle

import cv2
import matplotlib.pyplot as plt
%matplotlib inline

# cextract pre-trained face detector
MTCNN_detector = MTCNN()
# load image (rgb)        
img_rgb = cv2.imread(human_files[20])
#convert image to grayscale
img_gray =  cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
#detect the face 
faces = MTCNN_detector.detect_faces(img_gray)

#print num of faces detected  in image
print('Numbrer of faces detected = {}'.format(len(faces)))
                                     
# get bounding box for each detected face
for x, y, w, h in faces:
    # add bounded box to the colored image
    # cv2.rectangle(image, start_point, end_point, color, thickness)
    cv2.rectangle(img_rgb, (x, y), (x+w, y+h), (255,0,0) , 2)
    
#Convert RGB image to RGB image for plotting
face_rgb = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2RGB)
#8. display the image, along with bounding box
plt.imshow(face_rgb)
plt.show()

Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [13]:
VGG16_model = models.vgg16(pretrained=True)

if use_cuda:
    VGG16_model = VGG16_model.cuda() 
else:
    print('cuda NOT avaliable...')
In [14]:
print(VGG16_model)
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace)
    (2): Dropout(p=0.5)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace)
    (5): Dropout(p=0.5)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

In [15]:
from torch.autograd import Variable

def predict_breed(img_path,model):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    Args:
        img_path: path to an image
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    
    # 1. Load image from its path
    image = Image.open(img_path)
    
    # 2. pre-process an image from the given img_path (convert image to tensor)
    data_transform  = transforms.Compose([
                                     transforms.Resize(256),
                                     transforms.CenterCrop(224),
                                     transforms.ToTensor(),
                                     transforms.Normalize((0.485, 0.456, 0.406),
                                                          (0.229, 0.224, 0.225))
                                    ])
    
    
    tensor_img = data_transform(image).float()
    tensor_img = tensor_img.unsqueeze(0)
    tensor_img = Variable(tensor_img)
    # 3. Move to cuda
    if use_cuda:
        tensor_img = tensor_img.cuda()
    
    #4. make prediction and move it to cuda
    output =  model(tensor_img)
    
    #5. Move to cpu
    if use_cuda:
        output = output.cpu()
        
    #5. Return the *index* of the predicted class for that image
    
    torch.no_grad()
    index = output.data.numpy().argmax() 
    
    return index

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [71]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path, model):

    index= predict_breed(img_path, model)          
    
    return  (151 <= index and index <= 268)

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

  • What percentage of the images in human_files_short have a detected dog? 2%
  • What percentage of the images in dog_files_short have a detected dog? 99%
In [17]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
from tqdm import tqdm_notebook as tqdm

def dog_detector_performance(files_short , file_name, model):
    counter = []
    incorrect_imgs = []
    
    [(incorrect_imgs.append(file)) if (bool(dog_detector(file, model))^bool(file_name =='dog')) else (counter.append(1))for file in tqdm(files_short) ]

    return sum(counter), incorrect_imgs   
In [18]:
total = 100
human_files_short = human_files[:total]
dog_files_short = dog_files[:total]

n_faces_in_human_files, error_list_human_files  = dog_detector_performance(human_files_short, 'human',VGG16_model)
n_dogs_in_dog_files  , error_list_dog_files     = dog_detector_performance(dog_files_short, 'dog',VGG16_model)


In [19]:
n_dogs_in_human_files = total - n_faces_in_human_files
print('Number of dogs detected in human files short is {}/{} images \t\t cost = {}%'.format(n_dogs_in_human_files, total,
                                                                                           n_dogs_in_human_files))
print('Number of dogs detected in dog files short is {}/{} images \t\t cost = {}%'.format(n_dogs_in_dog_files, total,
                                                                                         100-n_dogs_in_dog_files))
Number of dogs detected in human files short is 1/100 images 		 cost = 1%
Number of dogs detected in dog files short is 100/100 images 		 cost = 0%
In [23]:
# print detector errors form human files 
show_erroneous(error_list_human_files, 2,2 ,25);
In [24]:
# print detector errors form dog files 
show_erroneous(error_list_dog_files, 2,5,15);
<matplotlib.figure.Figure at 0x7fa4f13898d0>

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

Report the performance using squeezenet1_1.

In [25]:
import torchvision.models as models

squeezenet11_model = models.squeezenet1_1(pretrained = True)

if use_cuda:
    squeezenet11_model = squeezenet11_model.cuda() 
else:
    print('cuda NOT avaliable...')
/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/models/squeezenet.py:94: UserWarning: nn.init.kaiming_uniform is now deprecated in favor of nn.init.kaiming_uniform_.
/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/models/squeezenet.py:92: UserWarning: nn.init.normal is now deprecated in favor of nn.init.normal_.
In [26]:
print(squeezenet11_model)
SqueezeNet(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(2, 2))
    (1): ReLU(inplace)
    (2): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=True)
    (3): Fire(
      (squeeze): Conv2d(64, 16, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(16, 64, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(16, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
    (4): Fire(
      (squeeze): Conv2d(128, 16, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(16, 64, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(16, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
    (5): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=True)
    (6): Fire(
      (squeeze): Conv2d(128, 32, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(32, 128, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(32, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
    (7): Fire(
      (squeeze): Conv2d(256, 32, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(32, 128, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(32, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
    (8): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=True)
    (9): Fire(
      (squeeze): Conv2d(256, 48, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(48, 192, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(48, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
    (10): Fire(
      (squeeze): Conv2d(384, 48, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(48, 192, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(48, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
    (11): Fire(
      (squeeze): Conv2d(384, 64, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(64, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
    (12): Fire(
      (squeeze): Conv2d(512, 64, kernel_size=(1, 1), stride=(1, 1))
      (squeeze_activation): ReLU(inplace)
      (expand1x1): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1))
      (expand1x1_activation): ReLU(inplace)
      (expand3x3): Conv2d(64, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
      (expand3x3_activation): ReLU(inplace)
    )
  )
  (classifier): Sequential(
    (0): Dropout(p=0.5)
    (1): Conv2d(512, 1000, kernel_size=(1, 1), stride=(1, 1))
    (2): ReLU(inplace)
    (3): AvgPool2d(kernel_size=13, stride=1, padding=0)
  )
)
In [27]:
total = 100
human_files_short = human_files[:total]
dog_files_short = dog_files[:total]

n_faces_in_human_files, error_list_human_files  = dog_detector_performance(human_files_short, 'human',squeezenet11_model)
n_dogs_in_dog_files   , error_list_dog_files    = dog_detector_performance(dog_files_short, 'dog',squeezenet11_model)


In [28]:
n_dogs_in_human_files = total - n_faces_in_human_files

print('Number of dogs detected in human files short is {}/{}   \t\t cost = {}%'.format(n_dogs_in_human_files, total,
                                                                                           n_dogs_in_human_files))
print('Number of dogs detected in dogs files short is {}/{}     \t\t cost = {}%'.format(n_dogs_in_dog_files, total,
                                                                                         100-n_dogs_in_dog_files))
Number of dogs detected in human files short is 1/100   		 cost = 1%
Number of dogs detected in dogs files short is 99/100     		 cost = 1%
In [29]:
show_erroneous(error_list_human_files, 2, 2,15)
In [30]:
show_erroneous(error_list_dog_files, 2, 3,15)

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador | Chocolate Labrador | Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dog_images/train, dog_images/valid, and dog_images/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [31]:
from torch.utils.data.sampler import SubsetRandomSampler
from torch.autograd import Variable
import random
import os
In [32]:
## Specify appropriate transforms
# https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html

data_transforms = {
    'train': transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomRotation(20),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'valid': transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'test': transforms.Compose([
        transforms.CenterCrop(256),
        transforms.Resize(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

print("Initializing Datasets and Dataloaders...")
data_dir = '/data/dog_images/'

image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
                  for x in ['train', 'valid', 'test']}
    
loaders_data = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size = 20,
                                              shuffle = True, num_workers = 0)
                  for x in ['train', 'valid', 'test']}
Initializing Datasets and Dataloaders...
In [33]:
loaders_data
Out[33]:
{'train': <torch.utils.data.dataloader.DataLoader at 0x7fa4f0231e80>,
 'valid': <torch.utils.data.dataloader.DataLoader at 0x7fa4e805a080>,
 'test': <torch.utils.data.dataloader.DataLoader at 0x7fa4e805a128>}
In [34]:
image_datasets
Out[34]:
{'train': Dataset ImageFolder
     Number of datapoints: 6680
     Root Location: /data/dog_images/train
     Transforms (if any): Compose(
                              RandomResizedCrop(size=(224, 224), scale=(0.08, 1.0), ratio=(0.75, 1.3333), interpolation=PIL.Image.BILINEAR)
                              RandomRotation(degrees=(-20, 20), resample=False, expand=False)
                              RandomHorizontalFlip(p=0.5)
                              ToTensor()
                              Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                          )
     Target Transforms (if any): None, 'valid': Dataset ImageFolder
     Number of datapoints: 835
     Root Location: /data/dog_images/valid
     Transforms (if any): Compose(
                              Resize(size=256, interpolation=PIL.Image.BILINEAR)
                              CenterCrop(size=(224, 224))
                              ToTensor()
                              Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                          )
     Target Transforms (if any): None, 'test': Dataset ImageFolder
     Number of datapoints: 836
     Root Location: /data/dog_images/test
     Transforms (if any): Compose(
                              CenterCrop(size=(256, 256))
                              Resize(size=224, interpolation=PIL.Image.BILINEAR)
                              ToTensor()
                              Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                          )
     Target Transforms (if any): None}
In [35]:
# Some statistics
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid', 'test']}

classes_name = image_datasets['train'].classes
n_classes = len(classes_name)


print('Number of train images = '     ,dataset_sizes['train']  ) 
print('Number of validation images = ',dataset_sizes['valid']  )
print('Number of test data images = ' ,dataset_sizes['test']   )
print('Number of classes = '          ,n_classes  )
Number of train images =  6680
Number of validation images =  835
Number of test data images =  836
Number of classes =  133

Show imges after augmatation

In [36]:
def imshow(img):
    
    img = img.transpose((1, 2, 0))
    
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    
    img = std * img + mean
    img = np.clip(img, 0, 1)
    
    plt.imshow(img)
##############################################################3
def show_shample_of_images (loaders_data, row, n_images, fig_size = (25, 5)):
    images, classes = next(iter(loaders_data))
    images = images.numpy() 
    fig = plt.figure(figsize=fig_size)

    for i in np.arange(n_images):
        ax = fig.add_subplot(row, n_images/row, i+1, xticks=[], yticks=[])
        imshow(images[i])
        class_names = image_datasets['train'].classes
        ax.set_title(class_names[classes[i]].split(".")[1])
In [49]:
show_shample_of_images(loaders_data['train'], 2, 20, fig_size = (24, 4))
In [50]:
show_shample_of_images(loaders_data['valid'], 2, 20, fig_size = (24, 4))
In [51]:
show_shample_of_images(loaders_data['test'], 2, 20, fig_size = (30, 5))

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer:

  1. Test and Validation datasets:

    • Extract a 224 × 224 pixels section from 256 × 256 pixels using Resize.
    • resized to (256, 256) using CenterCrop.
      • by resetting the images width and height.
    • Normalization by [0.485, 0.456, 0.406], [0.229, 0.224, 0.225].
  2. Train dataset :

    • Extract a 224 × 224 pixels section from 256 × 256 pixels using RandomResizedCrop.
    • Random Rotation by angle = 20 using RandomRotation(20).
    • Random Horizontal Flip using RandomHorizontalFlip().
    • Normalization by [0.485, 0.456, 0.406], [0.229, 0.224, 0.225].

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [56]:
!pip install torchsummary 
Collecting torchsummary
  Downloading https://files.pythonhosted.org/packages/7d/18/1474d06f721b86e6a9b9d7392ad68bed711a02f3b61ac43f13c719db50a6/torchsummary-1.5.1-py3-none-any.whl
Installing collected packages: torchsummary
Successfully installed torchsummary-1.5.1
In [37]:
conv_channels = {
             'layer0'  :3, 
             'layer1'  :16,
             'layer2'  :32,
             'layer3'  :64,
             'layer4'  :128,
             'layer5'  :256,
            }

hparameters={
             'n_batches'  : 128,
             'n_epochs'   : 10,
             'n_fc_nodes' : 512,
             'learning_rate' :0.01 ,
             'momentum'      : 0.9,
            }

hparameters['n_classes'] = n_classes

hparameters
Out[37]:
{'n_batches': 128,
 'n_epochs': 10,
 'n_fc_nodes': 512,
 'learning_rate': 0.01,
 'momentum': 0.9,
 'n_classes': 133}
In [38]:
# define the CNN architecture

class Net(nn.Module):
    ### TODO: choose an architecture, and complete the class
    def __init__(self):
        super(Net, self).__init__()
        
        ## Define Convolution layers 
        self.conv1 = nn.Conv2d (conv_channels['layer0'], conv_channels['layer1'], kernel_size = 3, padding = 1 , stride = 1)  
        self.conv2 = nn.Conv2d (conv_channels['layer1'], conv_channels['layer2'], kernel_size = 3, padding = 1 , stride = 1)  
        self.conv3 = nn.Conv2d (conv_channels['layer2'], conv_channels['layer3'], kernel_size = 3, padding = 1 , stride = 1) 
        self.conv4 = nn.Conv2d (conv_channels['layer3'], conv_channels['layer4'], kernel_size = 3, padding = 1 , stride = 1) 
        self.conv5 = nn.Conv2d (conv_channels['layer4'], conv_channels['layer5'], kernel_size = 3, padding = 1 , stride = 1) 
        
        self.pool = nn.MaxPool2d(2,2)
        self.dropout = nn.Dropout(0.3)
        
        # Define BatchNormalization 
        self.bn_1 = nn.BatchNorm2d(conv_channels['layer1'])
        self.bn_2 = nn.BatchNorm2d(conv_channels['layer2'])
        self.bn_3 = nn.BatchNorm2d(conv_channels['layer3'])
        self.bn_4 = nn.BatchNorm2d(conv_channels['layer4'])
        self.bn_5 = nn.BatchNorm2d(conv_channels['layer5'])
        
        ## Define fully connected layers
        
        self.fc1 = nn.Linear(conv_channels['layer5']*7*7, hparameters['n_fc_nodes'])
        self.fc2 = nn.Linear(hparameters['n_fc_nodes']  , hparameters['n_fc_nodes'])
        self.output = nn.Linear( hparameters['n_fc_nodes'], hparameters['n_classes'])
    
    def forward(self, x):
####################### Define forward behavior ######################################
                        #CONV_1
        x = F.relu(self.conv1(x))           #=> img = (224, 224)  n_channels : 3 ==> 16
        x = self.bn_1(self.pool(x))         #=> img = (112, 112)  n_channels = 16
        
                        #CONV_2
        x = F.relu(self.conv2(x))           #=> img = (112, 112)  n_channels : 16 ==> 32
        x = self.bn_2(self.pool(x))         #=> img = (56, 56)    n_channels = 32
        
                        #CONV_3
        x = F.relu(self.conv3(x))           #=> img = (56, 56)    n_channels : 32 ==> 64
        x = self.bn_3(self.pool(x))         #=> img = (28, 28)    n_channels = 64
        
                        #CONV_4
        x = F.relu(self.conv4(x))            #=> img = (28, 28)    n_channels : 64 ==> 128
        x = self.bn_4(self.pool(x))          #=> img = (14, 14)    n_channels = 128
        
                        #CONV_5
        x = F.relu(self.conv5(x))             #=> img = (14, 14)    n_channels : 128 ==> 256
        x = self.bn_5(self.pool(x))           #=> img = (7, 7)      n_channels = 256
    
####################### FLATTEN ####################################################                       
        x = x.view(x.size(0), conv_channels['layer5']*7*7) # n_channels * weidth * height 
#####################################################################################

                        #FULLY-CONNECTED_1 (HIDDEN)
        x = F.relu(self.fc1(x))
        x = self.dropout(x)
                        #FULLY-CONNECTED_2 (HIDDEN)
        x = F.relu(self.fc2(x))
        x = self.dropout(x)
                        #FULLY-CONNECTED_3 (OUTPUT)
        x = self.output(x)
        
        return x
#####################################################################################

# Create new model
model_scratch = Net()
In [39]:
# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()
In [40]:
from torchsummary import summary

summary(model_scratch, (3, 224, 224))
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 16, 224, 224]             448
         MaxPool2d-2         [-1, 16, 112, 112]               0
       BatchNorm2d-3         [-1, 16, 112, 112]              32
            Conv2d-4         [-1, 32, 112, 112]           4,640
         MaxPool2d-5           [-1, 32, 56, 56]               0
       BatchNorm2d-6           [-1, 32, 56, 56]              64
            Conv2d-7           [-1, 64, 56, 56]          18,496
         MaxPool2d-8           [-1, 64, 28, 28]               0
       BatchNorm2d-9           [-1, 64, 28, 28]             128
           Conv2d-10          [-1, 128, 28, 28]          73,856
        MaxPool2d-11          [-1, 128, 14, 14]               0
      BatchNorm2d-12          [-1, 128, 14, 14]             256
           Conv2d-13          [-1, 256, 14, 14]         295,168
        MaxPool2d-14            [-1, 256, 7, 7]               0
      BatchNorm2d-15            [-1, 256, 7, 7]             512
           Linear-16                  [-1, 512]       6,423,040
          Dropout-17                  [-1, 512]               0
           Linear-18                  [-1, 512]         262,656
          Dropout-19                  [-1, 512]               0
           Linear-20                  [-1, 133]          68,229
================================================================
Total params: 7,147,525
Trainable params: 7,147,525
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 17.82
Params size (MB): 27.27
Estimated Total Size (MB): 45.66
----------------------------------------------------------------

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer:

  • 5 CONV layers are used with kernal size = 3, stride = 1 and padding = 1
  • Channels used (16, 32, 64, 128, 256).
  • Each CONV followed by a max pooling layer of 2*2.
  • convert multi-dimantial to vector(flatten).
  • Two fully connected layer.
  • Relu activations are used after each layers except the last one.
  • Dropout is applied with the probability of 0.3 after each fully connected layer .

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [41]:
### select loss function
criterion_scratch = nn.CrossEntropyLoss()

### select optimizer
optimizer_scratch = optim.SGD(model_scratch.parameters() , lr = hparameters['learning_rate'], momentum=hparameters['momentum'])
# scheduler = optim.lr_scheduler.StepLR(optimizer_scratch, step_size=100, gamma=0.9)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [42]:
import time 
import numpy as np

def train(num_epochs,model, dataloaders, criterion, optimizer, use_cuda, save_path):
    
    val_acc_history=[]
    val_loss_history=[]
    
    train_acc_history=[]
    train_loss_history=[]
    
    valid_loss_min = np.Inf
    best_loss = np.Inf
    no_improve = 0
    early_stop = False
    
    since = time.time()
    for epoch in range(1, num_epochs + 1):
        start_epoch = time.time()
        print('Epoch {}/{}'.format(epoch, num_epochs))

        # Each epoch has a training and validation phase
        for phase in ['train', 'valid']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for batch_idx, (inputs, labels) in enumerate(dataloaders[phase]):
                
                if use_cuda:
                    inputs, labels = inputs.cuda(), labels.cuda()
                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    # Get model outputs and calculate loss
                    # Special case for inception because in training it has an auxiliary output. In train
                    #   mode we calculate the loss by summing the final output and the auxiliary output
                    #   but in testing we only consider the final output.
                    outputs = model(inputs)
                    loss = criterion(outputs, labels)

                    _, preds = torch.max(outputs, 1)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()
                        
                    if  batch_idx % 4 == 0 :
                        print('-',end='')

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

            epoch_loss = running_loss / len(dataloaders[phase].dataset)
            epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)

            print('\n{} epoch \t Loss: {:.6f} \t Accuracy: {:.6f}'.format(phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'valid' and epoch_loss < best_loss:
                print('-'*84)
                print('\nValidation loss decreased ({:.6f} ----> {:.6f})  Saving model...'.format(best_loss, epoch_loss))
                
                best_loss = epoch_loss
                torch.save(model.state_dict(), save_path)
                no_improve = 0
                
            elif phase == 'valid' and epoch_loss > best_loss:
                no_improve += 1
            
            if phase == 'valid':
                val_acc_history.append(epoch_acc)
                val_loss_history.append(epoch_loss)
            else:
                train_acc_history.append(epoch_acc)
                train_loss_history.append(epoch_loss)
            
            if epoch > 2 and no_improve == 3:
                print('Early stopping!' )
                early_stop = True
            else:
                early_stop = False

            # Check early stopping condition
            if early_stop:
                print("Stopped")
                break
                
        epoch_time = time.time() - start_epoch
        print('Epoch takes {:.0f} min {:.0f} sec'.format(epoch_time // 60,epoch_time % 60))

        print('='*84)

    time_elapsed = time.time() - since
    print('Training complete in {:.0f} min {:.0f} sec'.format(time_elapsed // 60, time_elapsed % 60))
    print('Best validation Loss: {:6f}'.format(best_loss))

    # load best model weights
    model.load_state_dict(torch.load(save_path))
    
    history = {'train_acc' :train_acc_history,
               'train_loss':train_loss_history,
               'val_acc'   :val_acc_history,
               'val_loss'  :val_loss_history,}
    
    return history , model
In [218]:
# train the model

loaders_scratch = loaders_data

history, model_scratch = train(hparameters['n_epochs'],model_scratch, 
                               loaders_scratch, criterion_scratch, 
                               optimizer_scratch, use_cuda, 'model_scratch.pt')
Epoch 1/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.707633 	 Accuracy: 0.028144
-----------
valid epoch 	 Loss: 4.505913 	 Accuracy: 0.043114
------------------------------------------------------------------------------------

Validation loss decreased (inf ----> 4.505913)  Saving model...
Epoch takes 1 min 49 sec
====================================================================================
Epoch 2/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.535550 	 Accuracy: 0.036976
-----------
valid epoch 	 Loss: 4.380635 	 Accuracy: 0.043114
------------------------------------------------------------------------------------

Validation loss decreased (4.505913 ----> 4.380635)  Saving model...
Epoch takes 1 min 49 sec
====================================================================================
Epoch 3/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.437874 	 Accuracy: 0.047605
-----------
valid epoch 	 Loss: 4.172264 	 Accuracy: 0.058683
------------------------------------------------------------------------------------

Validation loss decreased (4.380635 ----> 4.172264)  Saving model...
Epoch takes 1 min 48 sec
====================================================================================
Epoch 4/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.356495 	 Accuracy: 0.050150
-----------
valid epoch 	 Loss: 4.093575 	 Accuracy: 0.062275
------------------------------------------------------------------------------------

Validation loss decreased (4.172264 ----> 4.093575)  Saving model...
Epoch takes 1 min 48 sec
====================================================================================
Epoch 5/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.283553 	 Accuracy: 0.062874
-----------
valid epoch 	 Loss: 3.969471 	 Accuracy: 0.087425
------------------------------------------------------------------------------------

Validation loss decreased (4.093575 ----> 3.969471)  Saving model...
Epoch takes 1 min 49 sec
====================================================================================
Epoch 6/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.228369 	 Accuracy: 0.063772
-----------
valid epoch 	 Loss: 4.070707 	 Accuracy: 0.082635
Epoch takes 1 min 48 sec
====================================================================================
Epoch 7/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.156755 	 Accuracy: 0.071407
-----------
valid epoch 	 Loss: 3.831638 	 Accuracy: 0.124551
------------------------------------------------------------------------------------

Validation loss decreased (3.969471 ----> 3.831638)  Saving model...
Epoch takes 1 min 48 sec
====================================================================================
Epoch 8/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.085730 	 Accuracy: 0.079940
-----------
valid epoch 	 Loss: 3.742410 	 Accuracy: 0.112575
------------------------------------------------------------------------------------

Validation loss decreased (3.831638 ----> 3.742410)  Saving model...
Epoch takes 1 min 48 sec
====================================================================================
Epoch 9/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 4.016447 	 Accuracy: 0.083832
-----------
valid epoch 	 Loss: 3.775446 	 Accuracy: 0.105389
Epoch takes 1 min 48 sec
====================================================================================
Epoch 10/10
------------------------------------------------------------------------------------
train epoch 	 Loss: 3.965250 	 Accuracy: 0.095509
-----------
valid epoch 	 Loss: 3.622497 	 Accuracy: 0.123353
------------------------------------------------------------------------------------

Validation loss decreased (3.742410 ----> 3.622497)  Saving model...
Epoch takes 1 min 48 sec
====================================================================================
Training complete in 18 min 3 sec
Best validation Loss: 3.622497
In [43]:
## load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))

Visualizing Convolutional Layer Filters

In [44]:
from torchvision.utils import make_grid

kernels = model_scratch.conv1.weight.detach().clone()
kernels = kernels - kernels.min()
kernels = kernels / kernels.max()
img = make_grid(kernels)
plt.imshow(img.permute(1, 2, 0))
Out[44]:
<matplotlib.image.AxesImage at 0x7fa4e27c3be0>

(VISUALIZATION) visual accuarcy and losses using tensorboard

doesn't work

In [ ]:
!pip install --upgrade torch
In [ ]:
!pip install tensorboard --upgrade
In [ ]:
!python -m pip install grpcio-tools
In [ ]:
!pip install tensorboard_logger
In [ ]:
# from torch.utils.tensorboard import SummaryWriter

# # Writer will output to ./runs/ directory by default
# writer = SummaryWriter('./runs/model_scratch_experiment_1')
In [92]:
import os
root_logdir = os.path.join(os.curdir, 'my_logs')
In [93]:
import time

def get_run_logdir():
    run_id = time.strftime('run_%Y_%m_%d-%H_%M_%S')
    return os.path.join(root_logdir, run_id)

run_logdir = get_run_logdir()
print(run_logdir)
./my_logs/run_2021_02_05-05_55_32
In [ ]:
# !pip uninstall tensorboard-plugin-wit 1.8.0
# y
In [ ]:
# !pip install -U transformers torch torchvision tensorboardX tf-nightly grpcio==1.24.3
In [95]:
%reload_ext tensorboard
%tensorboard --logdir=./my_logs --port=6006
The tensorboard module is not an IPython extension.
UsageError: Line magic function `%tensorboard` not found.

(VISUALIZATION) visual accuarcy and losses using matplotlib

In [234]:
history
Out[234]:
{'train_acc': [tensor(1.00000e-02 *
         2.8144, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         3.6976, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         4.7605, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         5.0150, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         6.2874, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         6.3772, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         7.1407, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         7.9940, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         8.3832, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         9.5509, dtype=torch.float64, device='cuda:0')],
 'train_loss': [4.707633178391142,
  4.535550408734533,
  4.437873536241269,
  4.356495017063118,
  4.283552628077433,
  4.228368934043154,
  4.156754684305477,
  4.085730373502492,
  4.016446593278896,
  3.9652497347243534],
 'val_acc': [tensor(1.00000e-02 *
         4.3114, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         4.3114, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         5.8683, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         6.2275, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         8.7425, dtype=torch.float64, device='cuda:0'), tensor(1.00000e-02 *
         8.2635, dtype=torch.float64, device='cuda:0'), tensor(0.1246, dtype=torch.float64, device='cuda:0'), tensor(0.1126, dtype=torch.float64, device='cuda:0'), tensor(0.1054, dtype=torch.float64, device='cuda:0'), tensor(0.1234, dtype=torch.float64, device='cuda:0')],
 'val_loss': [4.505913483168551,
  4.38063481325161,
  4.172263573743626,
  4.093574763772017,
  3.9694711462466303,
  4.070707152703565,
  3.83163824338399,
  3.742409698977442,
  3.7754464192304784,
  3.622496924714414]}
In [45]:
train_acc = []
valid_acc = []

train_acc = [acc.cpu().numpy() for acc in history['train_acc']]
valid_acc = [acc.cpu().numpy() for acc in history['val_acc']]

plt.title("Training Accuacy VS Validation Accuracy.")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.plot(range(1,hparameters['n_epochs']+1),train_acc,label="Training Accuacy")
plt.plot(range(1,hparameters['n_epochs']+1),valid_acc,label="Validation Accuracy")

plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()

plt.savefig('Training Accuacy VS Validation Accuracy - model scratch.png')
print('Image saved!')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-45-81b302a57768> in <module>()
      2 valid_acc = []
      3 
----> 4 train_acc = [acc.cpu().numpy() for acc in history['train_acc']]
      5 valid_acc = [acc.cpu().numpy() for acc in history['val_acc']]
      6 

NameError: name 'history' is not defined
In [290]:
import numpy as np
plt.title("Training Loss VS Validation Loss.")
plt.xlabel("Epochs")
plt.ylabel("Loss")

plt.plot(range(1,hparameters['n_epochs']+1),history['train_loss'],label="Training Loss")
plt.plot(range(1,hparameters['n_epochs']+1),history['val_loss'],label="Validation Loss")

plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()

plt.savefig('Training Loss VS Validation Loss - model scratch.png')
print('Image saved!')
Image saved!
<matplotlib.figure.Figure at 0x7f420e769dd8>

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [237]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
        
        print('-',end='')
                    
    print('\nTest Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))
    

# call test function    
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
------------------------------------------
Test Loss: 3.759394


Test Accuracy: 11% (94/836)

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [46]:
## TODO: Specify data loaders
loaders_transfer = loaders_data
In [47]:
loaders_transfer
Out[47]:
{'train': <torch.utils.data.dataloader.DataLoader at 0x7fa4f0231e80>,
 'valid': <torch.utils.data.dataloader.DataLoader at 0x7fa4e805a080>,
 'test': <torch.utils.data.dataloader.DataLoader at 0x7fa4e805a128>}

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [48]:
## TODO: Specify model architecture 
model_transfer = models.densenet161(pretrained=True)

for param in model_transfer.parameters():
    param.requires_grad = False
/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/models/densenet.py:212: UserWarning: nn.init.kaiming_normal is now deprecated in favor of nn.init.kaiming_normal_.
In [49]:
n_features = model_transfer.classifier.in_features
model_transfer.classifier = nn.Linear(n_features, hparameters['n_classes'])
In [50]:
if use_cuda:
    model_transfer = model_transfer.cuda()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [51]:
criterion_transfer = nn.CrossEntropyLoss()

optimizer_transfer = torch.optim.SGD(model_transfer.classifier.parameters(),
                                      lr=hparameters['learning_rate'],
                                     momentum = hparameters['momentum'])

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [ ]:
# train the model
model_transfer, transfer_history =train(
                                        3,
                                        model_transfer,loaders_transfer,
                                        criterion_transfer,optimizer_transfer, use_cuda, 'model_transfer.pt')

# load the model that got the best validation accuracy (uncomment the line below)
Epoch 1/3
------------------------------------------------------------------------------------
train epoch 	 Loss: 0.964212 	 Accuracy: 0.733084
-----------
valid epoch 	 Loss: 0.478869 	 Accuracy: 0.853892
------------------------------------------------------------------------------------

Validation loss decreased (inf ----> 0.478869)  Saving model...
Epoch takes 3 min 53 sec
====================================================================================
Epoch 2/3
------------------------------------------------------------------------------------
train epoch 	 Loss: 0.894905 	 Accuracy: 0.747305
-----------
valid epoch 	 Loss: 0.402014 	 Accuracy: 0.880240
------------------------------------------------------------------------------------

Validation loss decreased (0.478869 ----> 0.402014)  Saving model...
Epoch takes 3 min 53 sec
====================================================================================
Epoch 3/3
---------------------------------------------------------
In [52]:
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
In [244]:
transfer_history
Out[244]:
DenseNet(
  (features): Sequential(
    (conv0): Conv2d(3, 96, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
    (norm0): BatchNorm2d(96, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (relu0): ReLU(inplace)
    (pool0): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
    (denseblock1): _DenseBlock(
      (denselayer1): _DenseLayer(
        (norm1): BatchNorm2d(96, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(96, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer2): _DenseLayer(
        (norm1): BatchNorm2d(144, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(144, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer3): _DenseLayer(
        (norm1): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(192, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer4): _DenseLayer(
        (norm1): BatchNorm2d(240, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(240, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer5): _DenseLayer(
        (norm1): BatchNorm2d(288, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(288, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer6): _DenseLayer(
        (norm1): BatchNorm2d(336, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(336, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
    )
    (transition1): _Transition(
      (norm): BatchNorm2d(384, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
      (conv): Conv2d(384, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (pool): AvgPool2d(kernel_size=2, stride=2, padding=0)
    )
    (denseblock2): _DenseBlock(
      (denselayer1): _DenseLayer(
        (norm1): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(192, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer2): _DenseLayer(
        (norm1): BatchNorm2d(240, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(240, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer3): _DenseLayer(
        (norm1): BatchNorm2d(288, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(288, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer4): _DenseLayer(
        (norm1): BatchNorm2d(336, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(336, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer5): _DenseLayer(
        (norm1): BatchNorm2d(384, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(384, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer6): _DenseLayer(
        (norm1): BatchNorm2d(432, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(432, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer7): _DenseLayer(
        (norm1): BatchNorm2d(480, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(480, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer8): _DenseLayer(
        (norm1): BatchNorm2d(528, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(528, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer9): _DenseLayer(
        (norm1): BatchNorm2d(576, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(576, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer10): _DenseLayer(
        (norm1): BatchNorm2d(624, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(624, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer11): _DenseLayer(
        (norm1): BatchNorm2d(672, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(672, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer12): _DenseLayer(
        (norm1): BatchNorm2d(720, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(720, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
    )
    (transition2): _Transition(
      (norm): BatchNorm2d(768, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
      (conv): Conv2d(768, 384, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (pool): AvgPool2d(kernel_size=2, stride=2, padding=0)
    )
    (denseblock3): _DenseBlock(
      (denselayer1): _DenseLayer(
        (norm1): BatchNorm2d(384, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(384, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer2): _DenseLayer(
        (norm1): BatchNorm2d(432, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(432, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer3): _DenseLayer(
        (norm1): BatchNorm2d(480, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(480, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer4): _DenseLayer(
        (norm1): BatchNorm2d(528, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(528, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer5): _DenseLayer(
        (norm1): BatchNorm2d(576, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(576, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer6): _DenseLayer(
        (norm1): BatchNorm2d(624, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(624, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer7): _DenseLayer(
        (norm1): BatchNorm2d(672, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(672, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer8): _DenseLayer(
        (norm1): BatchNorm2d(720, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(720, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer9): _DenseLayer(
        (norm1): BatchNorm2d(768, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(768, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer10): _DenseLayer(
        (norm1): BatchNorm2d(816, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(816, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer11): _DenseLayer(
        (norm1): BatchNorm2d(864, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(864, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer12): _DenseLayer(
        (norm1): BatchNorm2d(912, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(912, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer13): _DenseLayer(
        (norm1): BatchNorm2d(960, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(960, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer14): _DenseLayer(
        (norm1): BatchNorm2d(1008, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1008, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer15): _DenseLayer(
        (norm1): BatchNorm2d(1056, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1056, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer16): _DenseLayer(
        (norm1): BatchNorm2d(1104, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1104, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer17): _DenseLayer(
        (norm1): BatchNorm2d(1152, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1152, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer18): _DenseLayer(
        (norm1): BatchNorm2d(1200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1200, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer19): _DenseLayer(
        (norm1): BatchNorm2d(1248, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1248, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer20): _DenseLayer(
        (norm1): BatchNorm2d(1296, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1296, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer21): _DenseLayer(
        (norm1): BatchNorm2d(1344, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1344, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer22): _DenseLayer(
        (norm1): BatchNorm2d(1392, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1392, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer23): _DenseLayer(
        (norm1): BatchNorm2d(1440, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1440, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer24): _DenseLayer(
        (norm1): BatchNorm2d(1488, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1488, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer25): _DenseLayer(
        (norm1): BatchNorm2d(1536, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1536, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer26): _DenseLayer(
        (norm1): BatchNorm2d(1584, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1584, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer27): _DenseLayer(
        (norm1): BatchNorm2d(1632, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1632, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer28): _DenseLayer(
        (norm1): BatchNorm2d(1680, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1680, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer29): _DenseLayer(
        (norm1): BatchNorm2d(1728, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1728, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer30): _DenseLayer(
        (norm1): BatchNorm2d(1776, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1776, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer31): _DenseLayer(
        (norm1): BatchNorm2d(1824, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1824, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer32): _DenseLayer(
        (norm1): BatchNorm2d(1872, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1872, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer33): _DenseLayer(
        (norm1): BatchNorm2d(1920, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1920, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer34): _DenseLayer(
        (norm1): BatchNorm2d(1968, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1968, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer35): _DenseLayer(
        (norm1): BatchNorm2d(2016, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(2016, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer36): _DenseLayer(
        (norm1): BatchNorm2d(2064, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(2064, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
    )
    (transition3): _Transition(
      (norm): BatchNorm2d(2112, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
      (conv): Conv2d(2112, 1056, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (pool): AvgPool2d(kernel_size=2, stride=2, padding=0)
    )
    (denseblock4): _DenseBlock(
      (denselayer1): _DenseLayer(
        (norm1): BatchNorm2d(1056, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1056, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer2): _DenseLayer(
        (norm1): BatchNorm2d(1104, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1104, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer3): _DenseLayer(
        (norm1): BatchNorm2d(1152, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1152, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer4): _DenseLayer(
        (norm1): BatchNorm2d(1200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1200, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer5): _DenseLayer(
        (norm1): BatchNorm2d(1248, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1248, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer6): _DenseLayer(
        (norm1): BatchNorm2d(1296, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1296, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer7): _DenseLayer(
        (norm1): BatchNorm2d(1344, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1344, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer8): _DenseLayer(
        (norm1): BatchNorm2d(1392, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1392, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer9): _DenseLayer(
        (norm1): BatchNorm2d(1440, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1440, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer10): _DenseLayer(
        (norm1): BatchNorm2d(1488, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1488, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer11): _DenseLayer(
        (norm1): BatchNorm2d(1536, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1536, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer12): _DenseLayer(
        (norm1): BatchNorm2d(1584, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1584, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer13): _DenseLayer(
        (norm1): BatchNorm2d(1632, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1632, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer14): _DenseLayer(
        (norm1): BatchNorm2d(1680, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1680, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer15): _DenseLayer(
        (norm1): BatchNorm2d(1728, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1728, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer16): _DenseLayer(
        (norm1): BatchNorm2d(1776, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1776, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer17): _DenseLayer(
        (norm1): BatchNorm2d(1824, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1824, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer18): _DenseLayer(
        (norm1): BatchNorm2d(1872, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1872, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer19): _DenseLayer(
        (norm1): BatchNorm2d(1920, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1920, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer20): _DenseLayer(
        (norm1): BatchNorm2d(1968, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(1968, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer21): _DenseLayer(
        (norm1): BatchNorm2d(2016, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(2016, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer22): _DenseLayer(
        (norm1): BatchNorm2d(2064, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(2064, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer23): _DenseLayer(
        (norm1): BatchNorm2d(2112, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(2112, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
      (denselayer24): _DenseLayer(
        (norm1): BatchNorm2d(2160, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu1): ReLU(inplace)
        (conv1): Conv2d(2160, 192, kernel_size=(1, 1), stride=(1, 1), bias=False)
        (norm2): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
        (relu2): ReLU(inplace)
        (conv2): Conv2d(192, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      )
    )
    (norm5): BatchNorm2d(2208, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (classifier): Linear(in_features=2208, out_features=133, bias=True)
)

(VISUALIZATION) visual accuarcy and losses using matplotlib

doesn't work

In [527]:
train_acc = []
valid_acc = []

train_acc = [acc.cpu().numpy() for acc in transfer_history['train_acc']]
valid_acc = [acc.cpu().numpy() for acc in transfer_history['val_acc']]

plt.title("Training Accuacy VS Validation Accuracy.")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.plot(range(1,hparameters['n_epochs']+1),train_acc,label="Training Accuacy")
plt.plot(range(1,hparameters['n_epochs']+1),valid_acc,label="Validation Accuracy")
plt.ylim((0,0.4))
plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()

plt.savefig('Training Accuacy VS Validation Accuracy - pretrained scratch.png')
print('Image saved!')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-527-5548f5771569> in <module>()
      2 valid_acc = []
      3 
----> 4 train_acc = [acc.cpu().numpy() for acc in transfer_history['train_acc']]
      5 valid_acc = [acc.cpu().numpy() for acc in transfer_history['val_acc']]
      6 

TypeError: 'DenseNet' object is not subscriptable
In [439]:
import numpy as np
plt.title("Training Loss VS Validation Loss.")
plt.xlabel("Epochs")
plt.ylabel("Loss")

plt.plot(range(1,hparameters['n_epochs']+1),transfer_history['train_loss'],label="Training Loss")
plt.plot(range(1,hparameters['n_epochs']+1),transfer_history['val_loss'],label="Validation Loss")

plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()

plt.savefig('Training Loss VS Validation Loss - pretrained scratch.png')
print('Image saved!')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-439-ceea355d2944> in <module>()
      4 plt.ylabel("Loss")
      5 
----> 6 plt.plot(range(1,hparameters['n_epochs']+1),transfer_history['train_loss'],label="Training Loss")
      7 plt.plot(range(1,hparameters['n_epochs']+1),transfer_history['val_loss'],label="Validation Loss")
      8 

TypeError: 'DenseNet' object is not subscriptable

Comparison with Model Trained from Scratch and model transfer

doesn't work

In [ ]:
scratch_val_Acc = []
pretrained_val_Acc = []

scratch_val_Acc = [acc.cpu().numpy() for acc in history['val_acc']]
pretrained_val_Acc = [acc.cpu().numpy() for acc in transfer_history['val_acc']]

plt.title("Scratch Model vs. Pretrained Model")
plt.xlabel("Training Epochs")
plt.ylabel("Validation Accuracy")

plt.plot(range(1,num_epochs+1),scratch_val_Acc,label="Pretrained-val-Acc")
plt.plot(range(1,num_epochs+1),pretrained_val_Acc,label="Scratch-Acc")

plt.ylim((0,0.5))
plt.xticks(np.arange(1, num_epochs+1, 1.0))
plt.legend()

plt.show()
plt.savefig('Scratch Model vs. Pretrained Model.png')
print('Image saved!')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [266]:
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
------------------------------------------
Test Loss: 0.794442


Test Accuracy: 76% (642/836)

Visualizing Convolutional Layer Filters

In [53]:
from extractor import Extractor

extractor = Extractor(list(model_transfer.children()))
extractor.activate()
extractor.info()
Out[53]:
{'Down-sample layers name': 'downsample',
 'Total CNN Layers': 1,
 'Total Sequential Layers': 1,
 'Total Downsampling Layers': 0,
 'Total Linear Layers': 1,
 'Total number of Bottleneck and Basicblock': 0,
 'Total Execution time': '0.00038 sec'}
In [55]:
# Visualising the filters
import cv2
import torchvision.transforms as transforms

# plt.figure(figsize=(6, 6))

plt.figure(figsize=(25, 25))
for index, filter in enumerate(extractor.CNN_weights[0]):
    if index == 64:
        break
    plt.subplot(8, 8, index + 1)
    plt.imshow(filter[0, :, :].detach(), cmap='gray')
    plt.axis('off')
plt.show()
img = cv2.cvtColor(cv2.imread('./images/Curly-coated_retriever_03896.jpg'), cv2.COLOR_BGR2GRAY)
plt.imshow(img, cmap='gray')
plt.show()
In [56]:
img_transform = transforms.Compose([
                                    transforms.ToPILImage(),
                                    transforms.Resize((128, 128)),
                                    transforms.ToTensor(),
                                    transforms.Normalize(0.5, 0.5)])

img = img_transform(img).float().unsqueeze(0)
  
featuremaps = [extractor.CNN_layers[0](img)]
for x in range(1, len(extractor.CNN_layers)):
    featuremaps.append(extractor.CNN_layers[x](featuremaps[-1]))

# # Visualising the featuremaps
for x in range(len(featuremaps)):
    plt.figure(figsize=(30, 30))
    layers = featuremaps[x][0, :, :, :].detach()
    for i, filter in enumerate(layers):
        if i == 64:
            break
        plt.subplot(8, 8, i + 1)
        plt.imshow(filter, cmap='gray')
        plt.axis('off')

    plt.savefig('featuremap/featuremap%s.png'%(x))

plt.show()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-56-05d4cf2de309> in <module>()
      5                                     transforms.Normalize(0.5, 0.5)])
      6 
----> 7 img = img_transform(img).float().unsqueeze(0)
      8 
      9 # # 3. Move to cuda

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, img)
     47     def __call__(self, img):
     48         for t in self.transforms:
---> 49             img = t(img)
     50         return img
     51 

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, pic)
    108 
    109         """
--> 110         return F.to_pil_image(pic, self.mode)
    111 
    112     def __repr__(self):

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/functional.py in to_pil_image(pic, mode)
    113                         'not {}'.format(type(npimg)))
    114 
--> 115     if npimg.shape[2] == 1:
    116         expected_mode = None
    117         npimg = npimg[:, :, 0]

IndexError: tuple index out of range

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [120]:
loaders_transfer = loaders_data

class_names = [item[4:].replace("_", " ") for item in loaders_transfer['train'].dataset.classes]

def predict_breed_transfer(img_path , model):
    
    img = Image.open(img_path)
    trans = transforms.Compose([transforms.Resize(256),
                            transforms.CenterCrop(244),
                            transforms.ToTensor(),
                            transforms.Normalize((0.5,0.5,.5),(0.5,0.5,0.5))])

    img = trans(img)[:3,:,:].unsqueeze(0)

    if use_cuda:
        model = model.cuda()
        img = img.cuda()

    model.eval()
    class_ = model(img)
    output = class_names[torch.argmax(class_)]

    return output

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [135]:
def run_app(img_path):
    # Detect if the photo id dog or not 
    if dog_detector(img_path) :
        #Say Hallo for the dog ^^
        print("Hello, Dog")
        #Predict the Dog breed 
        Class = predict_breed_transfer(img_path , model_transfer)
        #Print the image 
        img = mpimg.imread(img_path)
        imgplot = plt.imshow(img)
        plt.axis('off')
        plt.show()
        print("The breed of the dog is :", Class)
        print("="*50)
        
    elif face_detector(img_path) :
        #Say Hello for the human^^
        print("Hello, Human")
        #Predict the human  resamplig of the dog breed
        Class = predict_breed_transfer(img_path , model_transfer)
        #Print the image 
        img = mpimg.imread(img_path)
        imgplot = plt.imshow(img)
        plt.axis('off')
        plt.show()
        print("The dog breed of the human is :", Class)
        print("="*50)
    else :
        print("The image is neither dog nor human there is an error ")
        img = mpimg.imread(img_path)
        imgplot = plt.imshow(img)
        plt.axis('off')
        plt.show()
        print("="*50)

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: (Three possible points for improvement)

In [136]:
# Create list of test image paths

for file in np.hstack((human_files[50:52], dog_files[50:52])):
    run_app(file)
Hello, Human
The dog breed of the human is : Silky terrier
==================================================
Hello, Human
The dog breed of the human is : Cavalier king charles spaniel
==================================================
Hello, Dog
The breed of the dog is : Mastiff
==================================================
Hello, Dog
The breed of the dog is : Mastiff
==================================================
In [ ]:
run_app('easy how to draw.jpeg') 
run_app('heba.jpg')
run_app('heba2.jpg')
run_app('drawing1.jpg')
run_app('drawing2.png')

OPTIONAL: Question for the reviewer

If you have any question about the starter code or your own implementation, please add it in the cell below.

For example, if you want to know why a piece of code is written the way it is, or its function, or alternative ways of implementing the same functionality, or if you want to get feedback on a specific part of your code or get feedback on things you tried but did not work.

Please keep your questions succinct and clear to help the reviewer answer them satisfactorily.

  • WHY my validation losses in model_scratch less than train loss?

  • On transfer_model WHY the history print the Net architecture?

  • I tried to visualize my result on tensorboard but all the trails failed.

  • Also tried to visualize feature map but failed.

In [ ]: